package org.catspaw.cherubim.matcher;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

public class JdkRegexStringMatcher extends AbstractStringMatcher {

	private boolean					usePatternCache;
	private Map<String, Pattern>	cache;

	public JdkRegexStringMatcher() {
	}

	public JdkRegexStringMatcher(boolean usePatternCache) {
		this.usePatternCache = usePatternCache;
		if (usePatternCache) {
			cache = new HashMap<String, Pattern>();
		}
	}

	public boolean match(String pattern, String target) {
		Pattern compiledPattern = null;
		if (usePatternCache) {
			compiledPattern = cache.get(pattern);
		}
		if (compiledPattern == null) {
			compiledPattern = compilePattern(pattern);
			if (usePatternCache) {
				cache.put(pattern, compiledPattern);
			}
		}
		return compiledPattern.matcher(target).matches();
	}

	public boolean match(Pattern pattern, String url) {
		return pattern.matcher(url).matches();
	}

	public Pattern compilePattern(String path) {
		return Pattern.compile(path);
	}
}
